package com.sinodata.bsm.inmp.task.gab;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.StatefulJob;

import com.sinodata.bsm.common.vo.Event;
import com.sinodata.bsm.common.vo.Res;
import com.sinodata.bsm.inmp.cache.CacheFactory;
import com.sinodata.bsm.inmp.cache.ResCache;
import com.sinodata.bsm.inmp.message.Messenger;
import com.sinodata.bsm.inmp.util.DBConnectionUtil;
import com.sinodata.bsm.inmp.util.FilePersistUtil;

/**
 * <p>
 * Description: 公安部数据网管事件类集成
 * i_incident表的 AF_SourceITCompId 字段关联c_itcomp表的P_Guid
 * </p>
 *
 * @author wangpeng
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2013-8-14 下午5:01:39          wangpeng        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class ShujiwangguanEventCollectJob implements StatefulJob {

    private static final String FILE_NAME = "gab_shujuwangguan_timestamp";
    private static final Logger logger = Logger.getLogger(ShujiwangguanEventCollectJob.class);
    private final ResCache resCache = (ResCache) CacheFactory.getCache(ResCache.class);
    //private static String lastTime = "2013-08-07 14:19:39";
    private static final SimpleDateFormat adf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final Long EVENT_TYPE_ID = 602100010100001L;
    private static final int LEVEL = 3;

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        String timestamp = getTimestamp();
        String sql = getSql(timestamp);
        Connection conn = null;
        Statement statement = null;
        ResultSet set = null;
        conn = DBConnectionUtil.getInstance().getStorConnection();
        List<Event> newEventList = new ArrayList<Event>();
        List<Event> confimedEventList = new ArrayList<Event>();
        try {
            statement = conn.createStatement();
            set = statement.executeQuery(sql);
            long timestampLong = adf.parse(timestamp).getTime();

            int setSize = set.getMetaData().getColumnCount();
            if (setSize > 0) {
                timestamp = buildEvent(set, timestampLong, newEventList, confimedEventList);
                Messenger.getInstance().sendEvent(newEventList);
                Thread.sleep(1000);
                Messenger.getInstance().sendEvent(confimedEventList);
            }
            logger.error("newEventList[" + newEventList.size() + "];confimedEventList[" + confimedEventList.size() + "]");
            if (timestamp != null) {
                FilePersistUtil.savePersistentData(FILE_NAME, timestamp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBConnectionUtil.getInstance().returnConn(conn);
        }

    }

    private String getTimestamp() {
        String timestamp;
        try {
            timestamp = (String) FilePersistUtil.getPersistentData(FILE_NAME);
            if (timestamp == null) {
                timestamp = adf.format(new Date());
            }
        } catch (Exception e) {
            logger.error("wenshidu>>> read data file " + FILE_NAME + " occered error", e);
            timestamp = adf.format(new Date());
        }
        return timestamp;
    }

    private String getSql(String timestamp) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT ");
        buffer.append("P_Guid, ");
        buffer.append("D_Title, ");
        buffer.append("D_StartTime, ");
        buffer.append("D_EndTime, ");
        buffer.append("AF_SourceITCompId ");
        buffer.append("FROM  ");
        buffer.append("i_incident i ");
        buffer.append("WHERE ");
        buffer.append("i.D_StartTime > STR_TO_DATE('");
        buffer.append(timestamp);
        buffer.append("','%Y-%m-%d %T') ");
        buffer.append("OR i.D_EndTime > STR_TO_DATE('");
        buffer.append(timestamp);
        buffer.append("','%Y-%m-%d %T') ");
        buffer.append("ORDER BY D_StartTime ASC");
        String sql = buffer.toString();
        logger.error("shujuwangguan>>>sql[" + sql + "]");
        return sql;
    }

    private String buildEvent(ResultSet set, long timestampLong, List<Event> newEventList, List<Event> confimedEventList) throws Exception {
        String lastTime = null;
        while (set.next()) {
            String objectId = set.getString(1);
            String msg = set.getString(2);
            String occurTimeStr = set.getString(3);
            String confirmTimeStr = set.getString(4);
            Date occurTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(occurTimeStr);
            Date confirmTime = confirmTimeStr != null ? new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(confirmTimeStr) : new Date();
            String internalId = set.getString(5);
            lastTime = adf.format(occurTime);
            Res res = resCache.getResIdByIId(internalId);
            if (res == null) {
                continue;
            }
            Long resId = res.getId();
            Integer level = LEVEL;
            Integer status = 0;
            if (confirmTime != null) {
                status = 2;
            }
            if (status == 0) {
                logger.error("shujuwangguan>>>status=" + status + " occur a new event");
                Event e = new Event();
                e.setResId(resId);
                e.setObjectId(objectId);
                e.setOccurTime(occurTime);
                e.setLevel(level);
                //e.setConfirmTime(confirmTime);
                e.setMsg(msg);
                e.setStatus(status);
                e.setEventTypeId(EVENT_TYPE_ID);
                e.setCatalog(1);
                newEventList.add(e);
            } else if (occurTime.getTime() < timestampLong) {
                logger.error("shujuwangguan>>>status=" + status + " occur a confime event");
                Event e2 = new Event();
                e2.setEventTypeId(EVENT_TYPE_ID);
                e2.setResId(resId);
                e2.setObjectId(objectId);
                e2.setOccurTime(occurTime);
                e2.setLevel(level);
                e2.setConfirmTime(confirmTime);
                e2.setMsg(msg);
                e2.setStatus(2);
                e2.setEventTypeId(EVENT_TYPE_ID);
                e2.setCatalog(2);
                confimedEventList.add(e2);
            } else {
                logger.error("shujuwangguan>>>status=" + status + ",occur two events");
                //先产生事件
                Event e = new Event();
                e.setEventTypeId(EVENT_TYPE_ID);
                e.setResId(resId);
                e.setObjectId(objectId);
                e.setOccurTime(occurTime);
                e.setLevel(level);
                //e.setConfirmTime(confirmTime);
                e.setMsg(msg);
                e.setStatus(0);
                e.setEventTypeId(EVENT_TYPE_ID);
                e.setCatalog(1);
                newEventList.add(e);
                //然后清除事件
                Event e2 = new Event();
                e2.setResId(resId);
                e2.setObjectId(objectId);
                e2.setOccurTime(occurTime);
                e2.setLevel(level);
                e2.setConfirmTime(confirmTime);
                e2.setMsg(msg);
                e2.setStatus(2);
                e2.setEventTypeId(EVENT_TYPE_ID);
                e2.setCatalog(2);
                confimedEventList.add(e2);
            }
        }
        return lastTime;
    }
}
